<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2019 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://demo.thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/ThinkAdmin
// | github 代码仓库：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\invitation\controller;

use app\company\service\DataService;
use library\Controller;
use think\Db;
/**工具类**/
use app\wechat\controller\WechatTool;
/**
 * 邀请函管理
 * Class User
 * @package app\worker\controller
 */
class Invitation extends Controller
{

    /**
     * 绑定当前数据表
     * @var string
     */
    protected $table = 'appointment';
    protected $view_table = 'view_appointment';
    protected $view_table_new = 'view_new_app_meeting_info_copy';
    /**
     * 邀请函管理(数据)
     * @auth true
     * @menu true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function index()
    {
        //var_dump($this->request->param(''));
        $dbconf = $this->getconfig('vister_db');
        $this->title = '邀请管理';
        $where ='';
        $uinfo = $this->getGuserinfo();
        // if($uinfo['db1']['authorize']!=1 && $uinfo['db1']['authorize']!=0){
        //     $check = $uinfo['db2']['companyid']==NULL?:'';
        //     if(!$check){
        //          $where = 'companyid = '.$uinfo['db2']['companyid'];
        //     }         
           
        // }
        switch ($uinfo['db1']['authorize']) {
            case '1':
                $where = 'type = 1';
                # code...
                break;
            case '2':
                $where = 'companyid = '.$uinfo['db2']['companyid'].' and type = 1';
                 # code...
                 break; 
            case '8':
                $company_list = Db::connect($dbconf)->table('property_relation')->field('incompany_id')->where('property_id = '.$uinfo['db2']['companyid'])->select();
                $company_arr =  array_column($company_list, 'incompany_id');
                $company_id = implode($company_arr, ",")?:0;
                $where = 'companyid in ('.$company_id.') and type = 1 ';

                 # code...
                 break; 
            default:
                $this->error('无权限查看');
                # code...
                break;
        }
        if($this->request->param('company_id')){
            $where = 'companyid = '.$this->request->param('company_id');
        }
        //search 
        $create_at_first=trim($this->request->param('create_at_first'))?strtotime($this->request->param('create_at_first')):'';
        $create_at_last=trim($this->request->param('create_at_last'))?strtotime($this->request->param('create_at_last'))+3600*24:'';
        $order = $this->request->param('order')?:'desc';
        $order_column = $this->request->param('order_column')?:'createtime';
        $order_str = $order_column.' '.$order;
		if(!$create_at_first||!$create_at_last){
	
			  $this->_query(Db::connect($dbconf)->table($this->view_table))->where($where)
                                                                            ->like('user_name,address,reson')
                                                                            ->equal('status')
                                                                            ->order($order_str)
                                                                            // ->order('createtime desc')
                                                                            ->page();
		
			}
			else{

            $this->_query(Db::connect($dbconf)->table($this->view_table))->where($where)
                                                                          ->where('visittime','between',[$create_at_first,$create_at_last])
                                                                          ->like('user_name,address,reson')
                                                                          ->equal('status')
                                                                          ->order($order_str)
                                                                          // ->order('createtime desc')
                                                                          ->page();
													
		}
    }	
    /**
     * 预约函(数据)
     * @auth true
     * @menu true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function indexapp()
    {
        $dbconf = $this->getconfig('vister_db');
        $this->title = '预约管理';
        $where ='';
        $uinfo = $this->getGuserinfo();
        // if($uinfo['db1']['authorize']!=1 && $uinfo['db1']['authorize']!=0){
        //     $check = $uinfo['db2']['companyid']==NULL?:'';
        //     if(!$check){
        //          $where = 'companyid = '.$uinfo['db2']['companyid'];
        //     }         
           
        // }
        switch ($uinfo['db1']['authorize']) {
            case '1':
                $where = 'type = 2';
                # code...
                break;
            case '2':
                $where = 'companyid = '.$uinfo['db2']['companyid'].' and type = 2';
                 # code...
                 break; 
            case '8':
                $company_list = Db::connect($dbconf)->table('property_relation')->field('incompany_id')->where('property_id = '.$uinfo['db2']['companyid'])->select();
                $company_arr =  array_column($company_list, 'incompany_id');
                $company_id = implode($company_arr, ",")?:0;
                $where = 'companyid in ('.$company_id.') and type = 2 ';

                 # code...
                 break; 
            default:
                $this->error('无权限查看');
                # code...
                break;
        }
        if($this->request->param('company_id')){
            $where = 'companyid = '.$this->request->param('company_id');
        }

        //search
        $create_at_first=trim($this->request->param('create_at_first'))?strtotime($this->request->param('create_at_first')):'';
        $create_at_last=trim($this->request->param('create_at_last'))?strtotime($this->request->param('create_at_last'))+3600*24:'';
        $order = $this->request->param('order')?:'desc';
        $order_column = $this->request->param('order_column')?:'createtime';
        $order_str = $order_column.' '.$order;
        
        if(!$create_at_first||!$create_at_last){
    
              $this->_query(Db::connect($dbconf)->table($this->view_table_new))->where($where)
                                                                             ->like('user_name,address,reson')
                                                                             ->equal('status')
                                                                             ->order($order_str)
                                                                             //->order('createtime desc')
                                                                             ->page();
        
            }
            else{

            $this->_query(Db::connect($dbconf)->table($this->view_table_new))->where($where)
                                                                          ->where('app_visittime','between',[$create_at_first,$create_at_last])
                                                                          ->like('user_name,address,reson')
                                                                          ->equal('status')
                                                                          ->order($order_str)
                                                                          //->order('createtime desc')
                                                                          ->page();
                                                    
        }
    }   
    /**
     * 添加邀请函
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function add()
    {
        return $this->fetch('qrcode');

        $dbconf = $this->getconfig('vister_db');
        $appointment = Db::connect($dbconf)->table('view_company')->select();
        $user = Db::connect($dbconf)->table('view_user')->select();
        $deptment= Db::connect($dbconf)->table('dept')->select();
        $this->assign('data',[
           'user'=>$user,
           'appointment'=>$appointment,
           'deptment'=>$deptment,

        ]);
        if($this->request->param('visit_name')){
          $visit_name = $this->request->param('visit_name');
          $reson = $this->request->param('reson');
          $address = $this->request->param('address');
          $companyid = $this->request->param('companyid');
          $user_name = $this->request->param('user_name');
          
          $data=[
              'visit_name'=>$visit_name,
              'reson'=>$reson,
              'address'=>$address,
              'companyid'=>$companyid,
            //   'user_name'=>$user_name,
              'createtime'=>time()
              ];
             
             $data_username=[
              'name'=>$name,
                 ];
          
            $res = Db::connect($dbconf)->table('appointment')->insert($data);
            $res1 = Db::connect($dbconf)->table('user')->insert($data_username);
            $this->success('添加邀请函成功','');
        }
        $this->_form($this->table, 'form');
    }


    /**
     * 修改邀请函
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function edit()
    {
        $dbconf = $this->getconfig('vister_db');
        $appointment = Db::connect($dbconf)->table('view_company')->select();
        $user = Db::connect($dbconf)->table('view_user')->select();
        $deptment= Db::connect($dbconf)->table('dept')->select();
        $this->assign('data',[
           'user'=>$user,
           'appointment'=>$appointment,
           'deptment'=>$deptment,

        ]);
        $this->_form($this->table, 'form');
    }

    /**
     * 权限表单数据处理
     * @param array $data 表单数据
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function _form_filter(&$data)
    {
        if ($this->request->isGet()) {
            $where = ['status' => '1', 'is_deleted' => '0'];
            $this->auths = Db::name('company_user_auth')->where($where)->order('sort desc,id desc')->select();
            array_unshift($this->auths, ['id' => '0', 'title' => '所有权限', 'path' => '/']);
            $data['svn_authorize'] = isset($data['svn_authorize']) ? explode(',', $data['svn_authorize']) : [];
        } else {
            if (isset($data['svn_authorize']) && is_array($data['svn_authorize'])) {
                $data['svn_authorize'] = join(',', $data['svn_authorize']);
            } else {
                $data['svn_authorize'] = '';
            }
            // $macs = [];
            // foreach (explode(PHP_EOL, preg_replace("/\s+/", PHP_EOL, trim($data['mobile_macs']))) as $mac) {
            //     if (DataService::applyMacValue($mac)) $macs[] = $mac;
            // }
            // $data['mobile_macs'] = join(PHP_EOL, array_unique($macs));
        }
    }

    /**
     * 变更邀请函状态||审核
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function state()
    {   
        $userinfo = $this->getGuserinfo();
        if($userinfo['db2']==NULL){$this->error('用户信息不全,请用手机端操作');}
        // var_dump($userinfo['db2']);
        $dbconf = $this->getconfig('vister_db');
        $id = $this->request->param('id');
        if(!$id){$this->error('信息不存在');}
        $status=$this->request->param('status');
        $type=$this->request->param('type'); //viss-预约审核
        $auditing=$this->request->param('auditing');//1审核通过 2审核不通过

        $where = ['id' => $id];
        $appointment_info = Db::connect($dbconf)->table('view_new_app_meeting_info_copy')->where($where)->find();
        if(!$appointment_info){$this->error('参数错误');}
        //改变邀请
        if($status=='1'){
            $data = [
                'status' => $status,
                'auditing' => 1,
            ];

        } 
        //预约审核   
        if($type == 'viss'){
            $data = [
                'auditing'=>$auditing,
            ];
            if($auditing==2){
                $data['status']=1;
            }

            $data['uid'] = $userinfo['db2']['id'];


            $meeting_data = [
                'appointment_uid' => $userinfo['db2']['id']?:NULL,
            ];
            $res = Db::connect($dbconf)->table('meeting')->where('uid ='.$userinfo['db2']['id'].' and appointmentid = '.$id)->data($meeting_data)->update();

            //推送消息-访客
            $keyword4 = $data['auditing']==1?'受访人接受了您的预约':'受访人拒绝了您的预约';
            $url = 'http://devs.zsicp.com/h5/#/pages/myyuyue/myyuyue';
            $send_data = [
            'template_id' => 'EeNfEuNHaQrLn2S9Rvf5tbKuh2HRez5GCJUOj0tD__w',
            'array' => [
                'first' => "预约申请审核通知",
                'keyword1' => $appointment_info['vister_name'],
                'keyword2' =>  $appointment_info['vister_mobile'],
                'keyword3' =>  $appointment_info['app_visittime'],
                'keyword4' => $keyword4,
                'remark'   => ''
                ],
            ];
            try{
                $find_openid = Db::connect($dbconf)->table('view_user')->where('id = '.$appointment_info['vister_uid'])->find();
                $result = WechatTool::send_WXtpl($find_openid['openid'],$send_data,$url);
            }catch(\Throwable $th){

            }


        }
            $this->_save(Db::connect($dbconf)->table($this->table),  $data,'',$where);
       
    }

	
	/**
	 * 查找添加时间
	 * @auth true
	 * @throws \think\Exception
	 * @throws \think\exception\PDOException
	 */
	// protected function _indexa_page_filter(&$list)
	// {	
	// 	// if($$this->request->isPost()){
	// 		$create_at_first=trim($this->request->param('create_at_first'));
	// 		$create_at_last=trim($this->request->param('create_at_last'));
	// 		var_dump($create_at_first);
	// 		var_dump($create_at_last);
	// 		// $this->userlist =Db::name('InvitationList')->whereTime('create_at', 'between', [$create_at_first, $create_at_last])->select();
	// 			// $list=Db::name('InvitationList')->where("create_at in ($create_at)")->order('id desc')->select();
	// 		 // var_dump($list);
	// 		  // return $this->assign('list',$list);
	// 		  // $this->_query($this->table)->like('userList')->equal('status')->page();	
	// 		  
	// 	$this->list=Db::name("InvitationList")->where('create_at','<= time',$create_at_last)
	// 		->where('create_at','> time',$create_at_first)
	// 		->select();
	// // var_dump($userlist);
	// 	// }
	// 	
	// 	
	// }
	
    /**
     * 删除邀请函
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function remove()
    {
           $dbconf = $this->getconfig('vister_db');
        // $this->_delete($this->table);
		if($this->request->isPost()){      
		$id=trim($this->request->param('id'));
		// dump($id);                                                     
// 		$data=Db::name('InvitationList')->where("id in ($id)")->delete();
			$data = Db::connect($dbconf)->table('appointment')->where("id in ($id)")->delete();
		if($data){
			$this->success('数据删除成功！');
		}
		}
    }
    /**
     * 邀请函详情
     * @auth         true
     * @throws           hink\Exception
     * @throws           hink\exception\PDOException
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-09-28T14:27:27+0800
     * @LastTime     2020-09-28T14:27:27+0800
     * @return       [type]                       [description]
     * @remark       此处id 为 视图id 具体信息请查表
     */
    public function details(){
        $dbconf = $this->getconfig('vister_db');
        
        $id = $this->request->param('id')?:$this->error('参数错误');
        $where = 'id ='.$id;
        $res = Db::connect($dbconf)->table('view_new_app_meeting_info_copy')->where($where)->find();

        $this->assign('list',$res);
        //$this->_query(Db::connect($dbconf)->table('view_new_app_meeting_info_copy'))->where($where)->find();
        if($this->request->param('type')=='viss'){
            return $this->fetch('detailsapp',['list'=>$res]);
        }else{  
            return $this->fetch();
        }
        

    }

}
